﻿using Syspetro.Aliyun;
using Syspetro.Core.AppDeal;
using Syspetro.Core.CommandBus;
using Syspetro.Core.Extensions;
using Syspetro.Core.Resources;
using Syspetro.Core.SysInterface;
using Syspetro.Deploy.Managers;
using Syspetro.DepRedis;
using System;

namespace BJ.AuthDomain.Commands
{
    /// <summary>
    /// 发送手机验证码(不需要登录)
    /// </summary>
    public class SendSMSCommand: Command
    {
        public string Phone { get; set; }
    }
    public interface ISendSMSCommandHandler : ICommandHandler<SendSMSCommand>, ITransientService
    {

    }
    public class SendSMSCommandHandler : CommandHandler<SendSMSCommand>, ISendSMSCommandHandler
    {
        readonly ISMSService _sMSService;
        public SendSMSCommandHandler(ISMSService sMSService)
        {
            _sMSService = sMSService;
        }

        public override SpActionResult<string> Execute(SendSMSCommand command)
        {
            var code = RandomGenerater.Captcha();
            var content = string.Format(SharedResource.TempleteSMS, code, _sMSService.GetValidTime());
            Serilog.Log.Information($"发送验证码：Phone：{command.Phone}，内容：{content}");
            var (status, msg) = _sMSService.Notify(command.Phone, content);
            Serilog.Log.Information($"发送结果：status：{status}，msg：{msg}");

            if (status)
            {
                RedisHelper redis = new("SMSCode");
                redis.StringSet(command.Phone, code, new TimeSpan(0, _sMSService.GetValidTime(), 0));
                return new SpActionResult<string> { Success = true, Msg = SharedResource.SendOk };
            }
            else
            {
                return new SpActionResult<string> { Success = false, Msg = msg };
            }
        }
    }
}
